package com.mh.study.springcloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;

/**
 * @author meng.han
 * @since 2022-04-11
 */
@Configuration
@EnableAuthorizationServer
public class OauthServerConfigurer extends AuthorizationServerConfigurerAdapter {

    private static final String SIGN_KEY = "MH123";

    private final AuthenticationManager authenticationManager;
    private final DataSource dataSource;
    private final MhAccessTokenConvertor mhAccessTokenConvertor;

    @Autowired
    public OauthServerConfigurer(AuthenticationManager authenticationManager,
                                 DataSource dataSource,
                                 MhAccessTokenConvertor mhAccessTokenConvertor) {
        this.authenticationManager = authenticationManager;
        this.dataSource = dataSource;
        this.mhAccessTokenConvertor = mhAccessTokenConvertor;
    }

    /**
     * 认证服务器最终是以api接口的方式对外提供服务（校验合法性并生成令牌、校验令牌等）
     * 那么，以api接口方式对外的话，就涉及到接口的访问权限，我们需要在这里进行必要的配置
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        // 允许客户端表单认证
        security.allowFormAuthenticationForClients()
                // 开启端口/oauth/token_key的访问权限
                .tokenKeyAccess("permitAll()")
                // 开启端口/oauth/check_token的访问权限
                .checkTokenAccess("permitAll()");
    }

    /**
     * 客户端详情配置，
     * ⽐如client_id，secret
     * 当前这个服务就如同QQ平台，拉勾网作为客户端需要QQ平台进行登录授权认证等，
     * 提前需要到QQ平台注册，QQ平台会给拉勾网颁发client_id等必要参数，表明客户端是谁
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        // 从内存中加载客户端详情
//        createInMemoryClientDetails(clients.inMemory());
        clients.withClientDetails(createJdbcDetails());
    }

    private ClientDetailsService createJdbcDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 从内存中加载客户端详情
     */
    private void createInMemoryClientDetails(InMemoryClientDetailsServiceBuilder memoryClientBuilder) throws Exception {
        // 客户端信息存储在什么地方，可以在内存中，可以在数据库里
        memoryClientBuilder.withClient("client_mh")
                .secret("abcxyz")
                // 指定客户端所能访问资源id清单，此处的资源id是需要在具体的资源服务器上也配置一样
                .resourceIds("autodeliver")
                // 认证类型/令牌颁发模式，可以配置多个在这里，但是不一定都用，具体使用哪种方式颁发token，需要客户端调用的时候传递参数指定
                .authorizedGrantTypes("password", "refresh_token")
                // 客户端的权限范围，此处配置为all全部即可
                .scopes("all");
    }

    /**
     * 这里配置token令牌相关的信息，token此时就是一个字符口中，token需要在服务器端存储。
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        // 指定token的存储方法
        endpoints.tokenStore(tokenStore())
                // token服务的一个描述，可以认为是token生成细节的描述，比如有效时间多少等
                .tokenServices(authorizationServerTokenServices())
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    private TokenStore tokenStore() {
//        return new InMemoryTokenStore();
        return new JwtTokenStore(jwtAccessTokenConverter());
    }


    private JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(SIGN_KEY);
        jwtAccessTokenConverter.setVerifier(new MacSigner(SIGN_KEY));
        jwtAccessTokenConverter.setAccessTokenConverter(mhAccessTokenConvertor);
        return jwtAccessTokenConverter;
    }

    private AuthorizationServerTokenServices authorizationServerTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setTokenStore(tokenStore());
        // 令牌增加器，设置为JWT访问令牌转换器
        defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter());
        // 设置令牌有效时长，一般设置为2个小时
        defaultTokenServices.setAccessTokenValiditySeconds(20);
        // 设置刷新令牌的时长
        defaultTokenServices.setRefreshTokenValiditySeconds(3 * 24 * 60 * 60);
        return defaultTokenServices;
    }

}
